from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp

class GAE_VersionControl:
  projects = []
  def getProjects(self):
    results = db.GqlQuery("SELECT * "
                            "FROM GAE_Project "
                            "ORDER BY create_date DESC LIMIT 10")
    for p in results:
      self.projects.append(p)
    return self.projects

  def addProject(self, project_name, description):
    project = GAE_Project(name=project_name, description=description)
    project.put()
    self.projects.append(project)
    return project
 
  def deleteProject(self, name):
    pass

  def getProject(self, name):
    result = None 
    results = db.GqlQuery("SELECT * "
                          "FROM GAE_Project "
                          "WHERE name=:1 LIMIT 1", name)
    for r in results:
      result = r 
    return result 

  def get_current_user_lists(self):
    results = db.GqlQuery("SELECT * "
                            "FROM GAE_Project "
                            "ORDER BY create_date DESC LIMIT 10")
    for p in results:
      self.projects.append(p)
    return self.projects

     
class GAE_Project(db.Model):
  name = db.StringProperty()
  description = db.StringProperty()
  create_date = db.DateTimeProperty(auto_now_add=True)

  def addFile(self, fileName, fileDesc, fileURL, fileAuthor, fileContent):
    file = GAE_ProjectFile(name=fileName, description=fileDesc, url=fileURL,
                     author=fileAuthor,content=fileContent)
    file.project=self
    file.put()
    return file

  def getFile(self, fileURL):
    result = None 
    results = db.GqlQuery("SELECT * "
                          "FROM GAE_ProjectFile "
                          "WHERE url =:1 and project=:2 LIMIT 1", fileURL, self.key())
    for r in results:
      result = r 
    return result 


class GAE_ProjectFile(db.Model):
  project = db.ReferenceProperty(GAE_Project, collection_name='files')
  name = db.StringProperty()
  description = db.StringProperty()
  url = db.StringProperty()
  author = db.StringProperty()
  content_type = db.StringProperty()
  content = db.BlobProperty()
  create_date = db.DateTimeProperty(auto_now_add=True)
  update_date = db.DateTimeProperty(auto_now_add=True)
  md5 = db.TextProperty()
  size = db.IntegerProperty()


